﻿using log4net;
using SuperSocket.SocketBase;
using SuperSocket.SocketBase.Config;
using SuperSocket.SocketBase.Protocol;
using System;
using System.Collections.Generic;
using System.Text;

namespace MeterSim.Socket {
    public class SocketServer: AppServer<SocketSession> {

        public static readonly ILog log = LogManager.GetLogger(typeof(SocketServer));

        public static string message = "";
        public static int interval = 200; // 广播间隔
        public static int port = 3000;

        System.Timers.Timer timer = new System.Timers.Timer { Enabled = false };

        public SocketServer() : base(new CommandLineReceiveFilterFactory(Encoding.UTF8, new BasicRequestInfoParser(":", "->"))) {
        }

        private string ConvertMessage(string hex) {
            string[] array = hex.Split(' ');
            List<byte> list = new List<byte>();
            foreach (var s in array) {
                list.Add(Convert.ToByte(s, 16));
            }
            return System.Text.Encoding.ASCII.GetString(list.ToArray());
        }

        private void SendMessage(object source, System.Timers.ElapsedEventArgs e) {
            if (message == "") {
                return;
            }
            IEnumerable<SocketSession> sessions = this.GetAllSessions();
            if (sessions == null) {
                return;
            }
            string data = ConvertMessage(message);
            foreach (var session in sessions) {
                session.Send(data, 0, data.Length);
            }
        }

        protected override bool Setup(IRootConfig rootConfig, IServerConfig config) {
            timer.Elapsed += new System.Timers.ElapsedEventHandler(SendMessage);

            return base.Setup(rootConfig, config);
        }

        protected override void OnStarted() {
            base.OnStarted();

            timer.Interval = interval;
            timer.Enabled = true;
        }

        protected override void OnStopped() {
            timer.Enabled = false;

            base.OnStopped();
        }
    }
}
